//
//  UIImage+WB.m


#import "UIImage+WB.h"

@implementation UIImage (WB)

/**图片适配*/
+ (UIImage *)imageWithName:(NSString *)name
{
    return [UIImage imageNamed:name];
}


+ (UIImage *)resizedImageWithName:(NSString *)name
{
   
    return [self resizedImageWithName:name left:0.5 top:0.5];
}

+ (UIImage *)resizedImageWithName:(NSString *)name left:(CGFloat)left top:(CGFloat)top;
{
    UIImage *image = [self imageWithName:name];
    return [image stretchableImageWithLeftCapWidth:image.size.width * left topCapHeight:image.size.height * top];
}


/** 设置圆形图片*/
- (UIImage *)cutCircleImage {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 获取上下文
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    // 设置圆形
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctr, rect);
    // 裁剪
    CGContextClip(ctr);
    // 将图片画上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


/**使用blend改变图片颜色*/
- (UIImage *)imageWithTintColor:(UIColor *)tintColor
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    [tintColor setFill];
    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
    UIRectFill(bounds);
    
    //Draw the tinted image in context
    [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
    
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return tintedImage;
}


/** 将图片压缩至指定大小KB*/
+(NSData *)scaleImage:(UIImage *)image toKb:(NSInteger)kb{
    
    kb *= 1024;
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.01f;
//    RZLog(@"压缩前:%fkb",(float)[UIImageJPEGRepresentation(image, 1) length] / 1024.0f);
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > kb && compression > maxCompression) {
        compression -= 0.01;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
//    RZLog(@"压缩后:%fkb",(float)[imageData length] / 1024.0f);
    return imageData;
}


//压缩图片尺寸
- (UIImage*)imageScaledToSize:(CGSize)newSize
{
    CGFloat scale = [[UIScreen mainScreen] scale];
    UIGraphicsBeginImageContextWithOptions(newSize, NO, scale);
    [self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext(); return newImage;
}
@end

